package com.android.delivery.activity.wangdian

import android.app.Activity
import android.content.Intent
import androidx.recyclerview.widget.RecyclerView
import com.android.delivery.R
import com.android.delivery.adapter.CitySendAdapter
import com.android.delivery.api.ApiService
import com.android.delivery.base.BaseListFragmet
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.dialog.NavigationDialog
import com.android.delivery.dialog.PayMethodDialog
import com.android.delivery.entity.Addr
import com.android.delivery.entity.Logistics
import com.android.delivery.entity.PayWxInfo
import com.android.delivery.entity.even.RefreshConfirmLanj
import com.android.delivery.entity.even.WxPayEvent
import com.android.delivery.receiver.PushDispatchListener
import com.android.delivery.receiver.PushNotifyManager
import com.android.delivery.util.ToastUtils
import com.android.delivery.util.pay.WXPayCommon
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.lzy.okgo.model.Response
import com.tencent.mm.opensdk.modelbase.BaseResp
import kotlinx.android.synthetic.main.include_refresh_layout.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 同城速递列表
 */
class CityAcceptFragment : BaseListFragmet<Logistics>(), PushDispatchListener {

    val TRANSFER_REQUESTCODE = 1;

    private val daiJieCheAdapter: CitySendAdapter by lazy {
        CitySendAdapter()
    }

    companion object {
        fun newInstance(): CityAcceptFragment {
            val fragment = CityAcceptFragment()
            return fragment
        }
    }

    override fun getEnableRefresh(): Boolean {
        return false
    }

    override fun initData() {
        super.initData()

        PushNotifyManager.getInstance().addPushDispatchListener(this)
    }

    override fun bindRecyclerView(recLv: RecyclerView?) {
        daiJieCheAdapter.setOnItemClickListener(object : CitySendAdapter.OnItemClickListener {
            override fun onLanJianOrder(logistics: Logistics) {
                ApiService.pick(this, logistics.logisticsNo!!, object : DialogCallback<LzyResponse<Any>>() {
                    override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                        onRefresh(refreshLayout)
                    }
                })
            }

            override fun onConfirmOrder(logistics: Logistics) {
                ApiService.cityConfirmDelivery(this, logistics.logisticsNo, object : DialogCallback<LzyResponse<Any>>() {
                    override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                        onRefresh(refreshLayout)
                    }
                })
            }

            override fun onCancelOrder(logistics: Logistics) {
                XPopup.Builder(activity) //                         .dismissOnTouchOutside(false)
                        .asConfirm("", "是否确认取消？",
                                "取消", "确定",
                                OnConfirmListener {
                                    ApiService.order_cancel(this, logistics.logisticsNo!!, object : DialogCallback<LzyResponse<Any>>() {
                                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                                            onRefresh(refreshLayout)
                                        }
                                    })
                                }, null, false)
                        .show()
            }

            override fun onTranferOrder(logistics: Logistics) {
                val intent = Intent(activity, RiderManagementActivity::class.java)
                intent.putExtra(Constants.TYPE, RiderManagementActivity.TYPE_TRANSFER)
                intent.putExtra(Constants.ORDER_ID, logistics.logisticsNo)
                startActivityForResult(intent, TRANSFER_REQUESTCODE)
            }

            override fun onPay(logistics: Logistics) {
                val payMethodDialog = PayMethodDialog.newInstance(logistics?.logisticsNo)
                payMethodDialog.setOnGuardDialogListener(object : PayMethodDialog.OnPayMethodDialogListener {

                    override fun onBalancePay(orderNo: String) {
                        balancePay(orderNo)
                    }

                    override fun selectPic() {

                    }

                    override fun onWxPay(orderNo: String) {
                        wxPay(orderNo)
                    }

                })
                payMethodDialog.show(childFragmentManager)
            }

            override fun onNavigation(addr: Addr) {
                val navigationDialog = NavigationDialog.newInstance(addr)
                navigationDialog.show(childFragmentManager)
            }

        })
        recLv!!.adapter = daiJieCheAdapter
    }

    private fun balancePay(orderNo: String) {
        ApiService.orderPayBalance(this, orderNo, object : DialogCallback<LzyResponse<Any>>() {
            override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                ToastUtils.showShort(activity, "支付成功")
                onRefresh(refreshLayout)
            }
        })
    }

    private fun wxPay(orderNo: String) {
        ApiService.orderPayWx(this, orderNo, object : DialogCallback<LzyResponse<PayWxInfo>>() {
            override fun onSuccess(response: Response<LzyResponse<PayWxInfo>>?) {
                val payWxInfo = response!!.body().data
                if (WXPayCommon.getInstance(activity).isWeixinAvilible) {
                    WXPayCommon.getInstance(activity).sendPayReq(payWxInfo)
                } else {
                    ToastUtils.showShort(activity, getString(R.string.wx_chat_install))
                }
            }
        })
    }

    override fun loadData(page: Int, pageCount: Int) {
        ApiService.getCitySend(this, 3, page, object : DialogCallback<LzyResponse<Logistics>>() {
            override fun onSuccess(response: Response<LzyResponse<Logistics>>) {
                finishRefreshaLayout()
                onGetDataSuc(response.body().data.records)
            }

            override fun onError(response: Response<LzyResponse<Logistics>>?) {
                super.onError(response)
                finishRefreshaLayout()
            }
        })
    }

    override fun getData(): MutableList<Logistics> {
        return daiJieCheAdapter.data
    }

    override fun bindData(isRefresh: Boolean, list: MutableList<Logistics>?) {
        if (isRefresh) daiJieCheAdapter.setNewData(list) else daiJieCheAdapter.addData(list!!)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: WxPayEvent) {
        if (item.payCode == BaseResp.ErrCode.ERR_OK) {
            ToastUtils.showShort(activity, "支付成功")
            onRefresh(refreshLayout)
        } else if (item.payCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
            ToastUtils.showShort(activity, "支付取消")
        } else {
            ToastUtils.showShort(activity, "支付失败")
        }
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == TRANSFER_REQUESTCODE) {
            if (resultCode == Activity.RESULT_OK) {
                onRefresh(refreshLayout)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refresh(refresh: RefreshConfirmLanj) {
        onRefresh(refreshLayout)
    }

    fun onAutoRefresh() {
        onRefresh(refreshLayout)
    }

    /**
     * 结束下拉刷新
     */
    private fun finishRefreshaLayout() {
    }

    override fun onReceOrder() {
        onAutoRefresh()
    }

    override fun onDestroy() {
        PushNotifyManager.getInstance().removePushDispatchListener(this)
        super.onDestroy()
    }
}